package com.example.remoteservicecustmom;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;

import com.example.remoteservic.IMyAidlInterface;

public class cusActivity extends AppCompatActivity {
    private Button bindService;
    //定义aidl接口变量
    private IMyAidlInterface mAIDL_Service;
    //内部匿名类接收binder
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name)
        {
        }

        //在Activity与Service建立关联时调用//使用AIDLService1.Stub.asInterface()方法获取服务器端返回的IBinder对象
        //            //将IBinder对象传换成了mAIDL_Service接口对象

        //通过该对象调用在MyAIDLService.aidl文件中定义的接口方法,从而实现跨进程通信H获取来自service的stub对象
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {


            mAIDL_Service = IMyAidlInterface.Stub.asInterface(service);


            try {
                mAIDL_Service.say();
            } catch (RemoteException e) {
                e.printStackTrace();
            }

        }

        ;
    };


        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_cus);

            bindService = (Button) findViewById(R.id.bind_service);

            //设置绑定服务的按钮
            bindService.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //通过Intent指定服务端的服务名称和所在包，与远程Service进行绑定
                    //参数与服务器端的action要一致,即"服务器包名.aidl接口文件名"
                    Intent intent = new Intent(" com.example.remote");

                    //Android5.0后无法只通过隐式Intent绑定远程Service
                    //需要通过setPackage()方法指定包名
                    intent.setPackage("com.example.remoteservic");
                    //绑定服务,传入intent和ServiceConnection对象z主要通过ServiceConnection服务的绑定与转化(将服务器的ibinder对象转化为接口变量的对象)
                    bindService(intent, connection, Context.BIND_AUTO_CREATE);

                }
            });



    }
   //class M
}
